package org.ljf.dao;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/**
 * @创建人 lIUJF
 * @创建时间 2018/12/21
 * @描述:
 */
public class RedisDao {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private JedisPool jedisPool;

	private RuntimeSchema<Seckill> schema = RuntimeSchema.createFrom(Seckill.class);//todo

	public RedisDao(String ip,int port){
		jedisPool = new JedisPool(ip,port);
	}

	//通过redis拿到secKill对象
	public Seckill getSeckill(long seckillId){
		//redis操作逻辑
		Jedis jedis = jedisPool.getResource();
		try {
			String key = "seckill" + seckillId;
			//并没有实现内部序列化操作。get---byte[]。序列化拿到object[Seckill].采用自定义序列化方式.protostuff:pojo
			byte[] bytes = jedis.get(key.getBytes());
			Seckill seckill = schema.newMessage();
			ProtobufIOUtil.mergeFrom(bytes, seckill, schema);//把字节对象按schema传递到空对象中
			//seckill被反序列化
			return seckill;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		} finally {
			jedis.close();
		}
		return null;
	}

	public String putSeckill(Seckill seckill){
		Jedis jedis = jedisPool.getResource();
		try {
			String key = "seckill" + seckill.getSeckillId();
			ProtobufIOUtil.toByteArray(seckill, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
			//超时缓存
			int timeout = 60 * 60;//设置一小时
			String result = jedis.setex(key.getBytes(), timeout, key.getBytes());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jedis.close();
		}
		return null;
	}
}
